<script lang="ts" setup>
import { createBannersApi, updateBannersApi, getBannersDetailApi } from "@/api/banners"
import { type CreateOrUpdateBannersRequestData } from "@/api/banners/types/index"
import { type FormInstance, type FormRules, ElMessage } from "element-plus"
import { useRouter } from "vue-router"
import { onBeforeUnmount, ref, shallowRef, onMounted } from "vue"
import PageTypeSelect from "./components/pageTypeSelect.vue"
import UploadImage from "@/components/UploadImage/index.vue"

defineOptions({
  // 命名当前组件
  name: "BannersOperate"
})
const router = useRouter()
const id: string = router.currentRoute.value.params.id as string
const loading = ref<boolean>(false)

//#region 增
const DEFAULT_FORM_DATA: CreateOrUpdateBannersRequestData = {
  id,
  index: 1,
  title: "",
  title_en: "",
  img_url: "",
  description: "",
  description_en: "",
  link: "",
  page_id: "",
  platform: "1"
}
const gotoList = () => {
  router.push("/banners")
}
const formRef = ref<FormInstance | null>(null)
const formData = ref<CreateOrUpdateBannersRequestData>(JSON.parse(JSON.stringify(DEFAULT_FORM_DATA)))
const formRules: FormRules<CreateOrUpdateBannersRequestData> = {
  index: [{ required: true, trigger: "blur", message: "请输入图片顺序索引" }],
  img_url: [{ required: true, trigger: "blur", message: "请上传轮播图片" }],
  page_id: [{ required: true, trigger: "blur", message: "请选择所属页面" }]
}
const handleCreateOrUpdate = () => {
  formRef.value?.validate((valid: boolean, fields) => {
    if (!valid) return console.error("表单校验不通过", fields)
    loading.value = true
    const api = !formData.value.id ? createBannersApi : updateBannersApi
    api(formData.value)
      .then(() => {
        ElMessage.success("操作成功")
        resetForm()
        gotoList()
      })
      .finally(() => {
        loading.value = false
      })
  })
}
const resetForm = () => {
  formRef.value?.clearValidate()
  formData.value = JSON.parse(JSON.stringify(DEFAULT_FORM_DATA))
}

//#region 查
const getBannersDetail = () => {
  if (!id) {
    return
  }
  getBannersDetailApi(id)
    .then(({ data }) => {
      formData.value = data
    })
    .catch(() => {
      formData.value = DEFAULT_FORM_DATA
    })
}
onMounted(async () => {
  getBannersDetail()
})
// 富文本
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})
const platformOptions = [
  {
    value: "1",
    label: "PC端"
  },
  {
    value: "2",
    label: "手机端"
  }
]
</script>

<template>
  <div class="app-container">
    <!-- 新增/修改 -->
    <el-card>
      <template #header>
        <div class="card-header">
          <h3>{{ id === undefined ? "新增轮播图" : "修改轮播图" }}</h3>
        </div>
      </template>
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" label-position="left">
        <el-form-item prop="index" label="顺序索引">
          <el-input-number v-model="formData.index" placeholder="请输入" :min="1" :precision="0" />
        </el-form-item>
        <el-form-item prop="page_id" label="所属页面">
          <page-type-select v-model="formData.page_id" />
        </el-form-item>
        <el-form-item prop="title" label="中文主题">
          <el-input v-model="formData.title" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="title_en" label="英文主题">
          <el-input v-model="formData.title_en" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="link" label="跳转链接">
          <el-input v-model="formData.link" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="img_url" label="图片">
          <upload-image v-model="formData.img_url" />
        </el-form-item>
        <el-form-item prop="platform" label="平台">
          <el-select v-model="formData.platform">
            <el-option v-for="item in platformOptions" :value="item.value" :label="item.label" :key="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item prop="description" label="中文描述">
          <el-input v-model="formData.description" placeholder="请输入" type="textarea" autosize />
        </el-form-item>
        <el-form-item prop="description_en" label="英文描述">
          <el-input v-model="formData.description_en" placeholder="请输入" type="textarea" autosize />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="gotoList">取消</el-button>
        <el-button type="primary" @click="handleCreateOrUpdate" :loading="loading">确认</el-button>
      </template>
    </el-card>
  </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;
  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}

.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}
</style>
